﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using YamlDotNet.Serialization;

namespace DWF.Studio.ProcessExecutor.Core.Utils
{
    internal static class YamlHelper
    {
        public static T Load<T>(string path, bool isMutex = false)
        {
            T config = default(T);

            Mutex mutex = null;
            if (isMutex)
            {
                var fileKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(path));
                mutex = new Mutex(false, fileKey);
            }

            try
            {
                mutex?.WaitOne();
                using (StreamReader reader = File.OpenText(path))
                {
                    var deserializerBuilder = new DeserializerBuilder().IgnoreUnmatchedProperties();
                    var yamlDeserializer = deserializerBuilder.Build();
                    config = yamlDeserializer.Deserialize<T>(reader);
                }
                mutex?.ReleaseMutex();
            }
            finally
            {
                mutex?.Dispose();
            }

            return config;
        }

        public static void Save<T>(T t, string path, bool isMutex = false)
        {
            Mutex mutex = null;
            if (isMutex)
            {
                var fileKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(path));
                mutex = new Mutex(false, fileKey);
            }

            try
            {
                mutex?.WaitOne();
                using (StreamWriter swriter = File.CreateText(path))
                {
                    Serializer yamlSerializer = new Serializer();
                    yamlSerializer.Serialize(swriter, t);
                }
                mutex?.ReleaseMutex(); ;
            }
            finally
            {
                mutex?.Dispose();
            }
        }

        public static void Save<T>(T t, Stream stream)
        {
            using (StreamWriter swriter = new StreamWriter(stream))
            {
                Serializer yamlSerializer = new Serializer();
                yamlSerializer.Serialize(swriter, t);
            }
        }
    }
}
